package org.wishwork.api.stock.in.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.wishwork.api.Api;
import org.wishwork.api.stock.in.query.response.StockInQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 采购入库查询
 * @author: WangYX
 * @create: 2022-04-11 17:23
 * @Version: 1.0.0
 **/

public class StockInQueryApi extends Api<List<StockInQueryResponse>, StockInQueryRequest> {

    private Context context;

    public StockInQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(StockInQueryRequest stockInQueryRequest) throws Exception {
        String url = "/open/purchasein/query";
        Map<String, Object> params = new HashMap<>();
        if (stockInQueryRequest.getPoIds() != null && stockInQueryRequest.getPoIds().size() > 0) {
            params.put("po_ids", stockInQueryRequest.getPoIds());
        }
        if (stockInQueryRequest.getStatus() != null && stockInQueryRequest.getStatus().size() > 0) {
            params.put("status", stockInQueryRequest.getStatus());
        }
        return HttpHelper.sendRequest(stockInQueryRequest, params, url);
    }

    @Override
    protected List<StockInQueryResponse> process(JSONObject data, StockInQueryRequest stockInQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<StockInQueryResponse> stockInQueryResponses = datas.toJavaList(StockInQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = stockInQueryRequest.getPageIndex();
            StockInQueryRequest build = stockInQueryRequest.toBuilder().pageSize(++pageIndex).build();
            List<StockInQueryResponse> business = business(build);
            stockInQueryResponses.addAll(business);
        }
        return stockInQueryResponses;
    }
}
